﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using ELGGAPI.Models;
using MySql.Data.MySqlClient;


namespace ELGGAPI.Data
{
    enum access
    {
        Friends = -2,
        Private = 0,
        Login_user = 1,
        Public = 2
    }
    public class GamePlayer
    {
        //Need to Re-Write according to the names in db
        [Key]
        public int GamePlayerID { get; set; }
        public string GamePlayerName { get; set; }
        public string GamePlayerEmail { get; set; }
        public string GamePlayererUserName { get; set; }
        public string GameProviderPassword { get; set; }
        public string PhotoURL { get; set; }
        public bool IsActive { get; set; }
        public string GameTag { get; set; }
        public string Profile { get; set; }

    }

    public class PlayerModel
    {
        public int? id { get; set; }

        public string name { get; set; }

        public string email { get; set; }

        public string username { get; set; }

        public string password { get; set; }

        public string photo { get; set; }

        public string game_tag { get; set; }

        public bool? active { get; set; }

        public IEnumerable<ProfileOptions> profileoptions { get; set; }
    }

    public class ProfileOptions
    {
        public string profilekey { get; set; }
        public string profilevalue { get; set; }
        public string profileaccess { get; set; }
    }
    public class ProfileImage
    {
        public string imagetype { get; set; }
        public string image { get; set; }
    }

    public class PlayeronlineModel
    {
        
            public int? id { get; set; }

            public string name { get; set; }

            public string username { get; set; }

            public string onlinstatus { get; set; }
       


    }
    public class PlayerContact
    {
        public int? contactid { get; set; }
        public int ProfileID { get; set; }
        public int? elggentityid { get; set; }
        public int relationshipid { get; set; }
        public string groups { get; set; }
        public string contactname { get; set; }
        public string address { get; set; }
        public string phone1 { get; set; }
        public string phone2 { get; set; }
        public string skype1 { get; set; }
        public string skype2 { get; set; }
        public string mobile1 { get; set; }
        public string mobile2 { get; set; }
        public string email1 { get; set; }
        public string email2 { get; set; }
        public string other1 { get; set; }
        public string other2 { get; set; }
    }

    public class PlayerMetrics
    {
        public int? playerid { get; set; }
        public int? gameid { get; set; }
        public string gamemetrics { get; set; }
    }
    public class InterestedGame
    {
        public int? playerid { get; set; }
        public int? gameid { get; set; }
    }

    public class PlayerDomainModles
    {
        public static Idclass RegisterUserAsPlayer(Idclass idclass)
        {
            PlayerModel playerModel = new PlayerModel();
            
            using (MySqlConnection connection = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand mySqlCommand = new MySqlCommand(APIHelper.DBName + "my_elggUser_Registration", connection))
                {
                    mySqlCommand.Parameters.Add("pElggEntityGUID", idclass.id);
                    mySqlCommand.CommandType = CommandType.StoredProcedure;
                    mySqlCommand.Connection.Open();
                    MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    while (mySqlDataReader.Read())
                        idclass.id = int.Parse(mySqlDataReader["userid"].ToString());
                    mySqlDataReader.Close();
                    connection.Close();
                }
            }
            return idclass;
        }
        public static Idclass AddInterestedGame(InterestedGame InterestedGame)
        {
            int UserId = 0;
            using (MySqlConnection con = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(APIHelper.DBName + "my_setInterestedgames", con))
                {
                    cmd.Parameters.Add("pelggentityguid", InterestedGame.playerid);
                    cmd.Parameters.Add("pgamesID", InterestedGame.gameid);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection.Open();
                    MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    while (dr.Read())
                    {
                        UserId = int.Parse(dr["UserId"].ToString());
                    }
                    dr.Close();
                    con.Close();
                }
            }
            return (new Idclass() { id = UserId });
        }

        public static PlayerMetrics AddGameMatrics(PlayerMetrics Metrics)
        {
            PlayerModel playerModel = new PlayerModel();
            using (MySqlConnection connection = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand mySqlCommand = new MySqlCommand(APIHelper.DBName + "my_gameMetrics", connection))
                {
                    mySqlCommand.Parameters.AddWithValue("pGameID", (object)Metrics.gameid);
                    mySqlCommand.Parameters.AddWithValue("pElggEntityGUID", (object)Metrics.playerid);
                    mySqlCommand.Parameters.AddWithValue("pgameMetrics", (object)Metrics.gamemetrics);
                    mySqlCommand.CommandType = CommandType.StoredProcedure;
                    mySqlCommand.Connection.Open();
                    MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    while (mySqlDataReader.Read())
                    {
                        Metrics.playerid = new int?(int.Parse(mySqlDataReader["pElggEntityGUID"].ToString()));
                        Metrics.gameid = new int?(int.Parse(mySqlDataReader["pGameID"].ToString()));
                    }
                    mySqlDataReader.Close();
                    connection.Close();
                }
            }
            return Metrics;
        }

        public static Idclass AddContact(PlayerContact PContact)
        {
            string connectionString = APIHelper.ConnectionString;
            int UserId = 0;

            using (MySqlConnection con = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand(APIHelper.DBName + "my_profileContactsInsertUpdate", con);

                cmd.CommandType = CommandType.StoredProcedure;
                if (PContact.contactid > 0)
                    cmd.Parameters.Add(new MySqlParameter("pContactID", PContact.contactid));
                else
                    cmd.Parameters.Add(new MySqlParameter("pContactID", DBNull.Value));
                if (PContact.elggentityid > 0)
                    cmd.Parameters.Add(new MySqlParameter("pElggentityGuid", PContact.elggentityid));
                else
                    cmd.Parameters.Add(new MySqlParameter("pElggentityGuid", DBNull.Value));

                cmd.Parameters.Add(new MySqlParameter("pProfileID", PContact.ProfileID));
                cmd.Parameters.Add(new MySqlParameter("pRelationshipID", PContact.relationshipid));
                cmd.Parameters.Add(new MySqlParameter("pGroups", PContact.groups));
                cmd.Parameters.Add(new MySqlParameter("pContactName", PContact.contactname));
                cmd.Parameters.Add(new MySqlParameter("pAddress", PContact.address));
                cmd.Parameters.Add(new MySqlParameter("pPhone1", PContact.phone1));
                cmd.Parameters.Add(new MySqlParameter("pPhone2", PContact.phone2));
                cmd.Parameters.Add(new MySqlParameter("pSkype2", PContact.skype2));
                cmd.Parameters.Add(new MySqlParameter("pSkype1", PContact.skype1));
                cmd.Parameters.Add(new MySqlParameter("pMobile1", PContact.mobile1));
                cmd.Parameters.Add(new MySqlParameter("pMobile2", PContact.mobile2));
                cmd.Parameters.Add(new MySqlParameter("pEmail1", PContact.email1));
                cmd.Parameters.Add(new MySqlParameter("pEmail2", PContact.email2));
                cmd.Parameters.Add(new MySqlParameter("pOther1", PContact.other1));
                cmd.Parameters.Add(new MySqlParameter("pOther2", PContact.other2));
                // Execute the command.
                cmd.Connection.Open();
                MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                while (dr.Read())
                {
                    UserId = int.Parse(dr["VcontactId"].ToString());
                }
                dr.Close();
                con.Close();
            }

            return (new Idclass() { id = UserId }); ;

        }
        public static Idclass AddPlayer(PlayerModel Player)
        {

            string connectionString = APIHelper.ConnectionString;
            int recCount = 0;
            int profilecount = 0;
            int UserId = 0;

            IEnumerable<ProfileOptions> profileoptions = Player.profileoptions;
            string profilexml = "";
            if (profileoptions !=null)
            foreach (ProfileOptions PO in profileoptions)
            {
                profilecount++;
                profilexml += "<Profile><ProfileName>" + PO.profilekey + "</ProfileName>";
                profilexml += "<ProfileText>" + PO.profilevalue + "</ProfileText>";
                profilexml += "<ProfileAccessID>" + PO.profileaccess + "</ProfileAccessID>";
                profilexml += "</Profile>";

            }
            using (MySqlConnection con = new MySqlConnection(connectionString))
            {
                MySqlCommand cmd = new MySqlCommand(APIHelper.DBName + "User_Registration", con);

                // Configure command and add parameters.
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new MySqlParameter("pDisplay_name", Player.name));
                cmd.Parameters.Add(new MySqlParameter("pLoopTime", profilecount));
                cmd.Parameters.Add(new MySqlParameter("pEmail_address", Player.email));
                cmd.Parameters.Add(new MySqlParameter("pUsername", Player.username));
                cmd.Parameters.Add(new MySqlParameter("pPassword", Player.password));
                cmd.Parameters.Add(new MySqlParameter("pActive", Player.active));
                cmd.Parameters.Add(new MySqlParameter("pPhoto", Player.photo));
                cmd.Parameters.Add(new MySqlParameter("pGameTag", Player.game_tag));
                cmd.Parameters.Add(new MySqlParameter("xml", profilexml));
                // Execute the command.
                cmd.Connection.Open();
                MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                //dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    recCount++;
                    UserId = int.Parse(dr["UserId"].ToString());

                }
                dr.Close();
                con.Close();
            }

            return (new Idclass() { id = UserId }); ;


        }

        public static List<PlayerModel> GetPortalUsers()
        {
            List<PlayerModel> list = new List<PlayerModel>();
            DataSet dataSet = new DataSet();
            using (MySqlConnection mySqlConnection = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand mySqlCommand = new MySqlCommand(APIHelper.DBName + "my_getElggUserExceptGamePlayer", mySqlConnection))
                {
                    mySqlCommand.Parameters.Add("UserID", DBNull.Value);
                    mySqlCommand.CommandType = CommandType.StoredProcedure;
                    using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mySqlCommand))
                    {
                        mySqlDataAdapter.Fill(dataSet);
                    }
                }
            }
            if (dataSet.Tables.Count > 0)
            {
                DataTable dataTable = dataSet.Tables[1];
                string stieurl = dataSet.Tables[0].Rows[0]["url"].ToString();
                foreach (DataRow dataRow in dataTable.Rows)
                {

                    PlayerModel playerModel = new PlayerModel();
                    playerModel.id = new int?(int.Parse(dataRow["UserID"].ToString()));
                    playerModel.name = dataRow["name"].ToString();
                    playerModel.username = dataRow["userName"].ToString();
                    playerModel.email = dataRow["email"].ToString();
                    string linpath = stieurl+"mod/profile/icondirect.php?joindate=" + dataRow["time_created"].ToString() + "&guid=" + playerModel.id + "&size=large";
                    playerModel.photo = linpath;
                    List<ProfileOptions> list2 = new List<ProfileOptions>();
                    if (DBNull.Value != dataRow["briefdescription"])
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "briefdescription",
                            profilevalue = dataRow["briefdescription"].ToString(),
                            profileaccess = dataRow["briefdescription_accessid"].ToString()
                        });
                    }
                    if (DBNull.Value != dataRow["description"])
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "description",
                            profilevalue = dataRow["description"].ToString(),
                            profileaccess = dataRow["description_accessid"].ToString()
                        });
                    }
                    if (DBNull.Value != dataRow["location"])
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "location",
                            profilevalue = dataRow["location"].ToString(),
                            profileaccess = dataRow["location_accessid"].ToString()
                        });
                    }
                    if (dataRow["interests"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "interests",
                            profilevalue = dataRow["interests"].ToString(),
                            profileaccess = dataRow["interests_accessid"].ToString()
                        });
                    }
                    if (dataRow["skills"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "skills",
                            profilevalue = dataRow["skills"].ToString(),
                            profileaccess = dataRow["skills_accessid"].ToString()
                        });
                    }
                    if (dataRow["contactemail"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "contactemail",
                            profilevalue = dataRow["contactemail"].ToString(),
                            profileaccess = dataRow["contactemail_accessid"].ToString()
                        });
                    }
                    if (dataRow["phone"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "phone",
                            profilevalue = dataRow["phone"].ToString(),
                            profileaccess = dataRow["phone_accessid"].ToString()
                        });
                    }
                    if (dataRow["mobile"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "mobile",
                            profilevalue = dataRow["mobile"].ToString(),
                            profileaccess = dataRow["mobile_accessid"].ToString()
                        });
                    }
                    if (dataRow["website"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "website",
                            profilevalue = dataRow["website"].ToString(),
                            profileaccess = dataRow["website_accessid"].ToString()
                        });
                    }
                    if (dataRow["twitter"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "twitter",
                            profilevalue = dataRow["twitter"].ToString(),
                            profileaccess = dataRow["twitter_accessid"].ToString()
                        });
                    }
                    playerModel.profileoptions = list2;
                    list.Add(playerModel);
                }
            }
            return list;
        }
        public static List<PlayerModel> GetPlayerList()
        {
            List<PlayerModel> list = new List<PlayerModel>();
            DataSet dataSet = new DataSet();
            using (MySqlConnection mySqlConnection = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand mySqlCommand = new MySqlCommand(APIHelper.DBName + "my_getPlayerProfile", mySqlConnection))
                {
                    mySqlCommand.Parameters.Add("UserID", DBNull.Value);
                    mySqlCommand.CommandType = CommandType.StoredProcedure;
                    using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mySqlCommand))
                    {
                        mySqlDataAdapter.Fill(dataSet);
                    }
                }
            }
            if (dataSet.Tables.Count > 0)
            {
                string stieurl = dataSet.Tables[0].Rows[0]["url"].ToString();
                DataTable dataTable = dataSet.Tables[1];
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    PlayerModel playerModel = new PlayerModel();
                    playerModel.id = new int?(int.Parse(dataRow["UserID"].ToString()));
                    playerModel.name = dataRow["name"].ToString();
                    playerModel.username = dataRow["userName"].ToString();
                    playerModel.email = dataRow["email"].ToString();
                    string linpath = stieurl+"mod/profile/icondirect.php?joindate=" + dataRow["time_created"].ToString() + "&guid=" + playerModel.id + "&size=large";
                    playerModel.photo = linpath;
                    List<ProfileOptions> list2 = new List<ProfileOptions>();
                    if (DBNull.Value != dataRow["briefdescription"])
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "briefdescription",
                            profilevalue = dataRow["briefdescription"].ToString(),
                            profileaccess = dataRow["briefdescription_accessid"].ToString()
                        });
                    }
                    if (DBNull.Value != dataRow["description"])
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "description",
                            profilevalue = dataRow["description"].ToString(),
                            profileaccess = dataRow["description_accessid"].ToString()
                        });
                    }
                    if (DBNull.Value != dataRow["location"])
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "location",
                            profilevalue = dataRow["location"].ToString(),
                            profileaccess = dataRow["location_accessid"].ToString()
                        });
                    }
                    if (dataRow["interests"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "interests",
                            profilevalue = dataRow["interests"].ToString(),
                            profileaccess = dataRow["interests_accessid"].ToString()
                        });
                    }
                    if (dataRow["skills"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "skills",
                            profilevalue = dataRow["skills"].ToString(),
                            profileaccess = dataRow["skills_accessid"].ToString()
                        });
                    }
                    if (dataRow["contactemail"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "contactemail",
                            profilevalue = dataRow["contactemail"].ToString(),
                            profileaccess = dataRow["contactemail_accessid"].ToString()
                        });
                    }
                    if (dataRow["phone"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "phone",
                            profilevalue = dataRow["phone"].ToString(),
                            profileaccess = dataRow["phone_accessid"].ToString()
                        });
                    }
                    if (dataRow["mobile"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "mobile",
                            profilevalue = dataRow["mobile"].ToString(),
                            profileaccess = dataRow["mobile_accessid"].ToString()
                        });
                    }
                    if (dataRow["website"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "website",
                            profilevalue = dataRow["website"].ToString(),
                            profileaccess = dataRow["website_accessid"].ToString()
                        });
                    }
                    if (dataRow["twitter"] != DBNull.Value)
                    {
                        list2.Add(new ProfileOptions
                        {
                            profilekey = "twitter",
                            profilevalue = dataRow["twitter"].ToString(),
                            profileaccess = dataRow["twitter_accessid"].ToString()
                        });
                    }
                    playerModel.profileoptions = list2;
                    list.Add(playerModel);
                }
            }
            return list;

        }
        public static PlayerModel GetPlayerInfoByToken(string pToken)
        {
            PlayerModel playerModel = new PlayerModel();
            DataSet dataSet = new DataSet();
            using (MySqlConnection mySqlConnection = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand mySqlCommand = new MySqlCommand(APIHelper.DBName + "my_getPlayerProfileByToken", mySqlConnection))
                {
                    mySqlCommand.Parameters.Add("pToken", pToken);
                    mySqlCommand.CommandType = CommandType.StoredProcedure;
                    using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mySqlCommand))
                    {
                        mySqlDataAdapter.Fill(dataSet);
                    }
                }
            }
            if (dataSet.Tables.Count > 0)
            {
                string siteurl = dataSet.Tables[0].Rows[0]["url"].ToString();
                DataTable dataTable = dataSet.Tables[1];
                if (dataTable.Rows.Count > 0)
                {
                    DataRow dataRow = dataTable.Rows[0];
                    
                    playerModel.id = new int?(int.Parse(dataRow["UserID"].ToString()));
                    playerModel.name = dataRow["name"].ToString();
                    playerModel.username = dataRow["userName"].ToString();
                    playerModel.email = dataRow["email"].ToString();
                    string linpath = siteurl+ "mod/profile/icondirect.php?joindate=" + dataRow["time_created"].ToString() + "&guid=" + playerModel.id + "&size=large";
                    playerModel.photo = linpath;
                    List<ProfileOptions> list = new List<ProfileOptions>();
                    if (DBNull.Value != dataRow["briefdescription"])
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "briefdescription",
                            profilevalue = dataRow["briefdescription"].ToString(),
                            profileaccess = dataRow["briefdescription_accessid"].ToString()
                        });
                    }
                    if (DBNull.Value != dataRow["description"])
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "description",
                            profilevalue = dataRow["description"].ToString(),
                            profileaccess = dataRow["description_accessid"].ToString()
                        });
                    }
                    if (DBNull.Value != dataRow["location"])
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "location",
                            profilevalue = dataRow["location"].ToString(),
                            profileaccess = dataRow["location_accessid"].ToString()
                        });
                    }
                    if (dataRow["interests"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "interests",
                            profilevalue = dataRow["interests"].ToString(),
                            profileaccess = dataRow["interests_accessid"].ToString()
                        });
                    }
                    if (dataRow["skills"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "skills",
                            profilevalue = dataRow["skills"].ToString(),
                            profileaccess = dataRow["skills_accessid"].ToString()
                        });
                    }
                    if (dataRow["contactemail"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "contactemail",
                            profilevalue = dataRow["contactemail"].ToString(),
                            profileaccess = dataRow["contactemail_accessid"].ToString()
                        });
                    }
                    if (dataRow["phone"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "phone",
                            profilevalue = dataRow["phone"].ToString(),
                            profileaccess = dataRow["phone_accessid"].ToString()
                        });
                    }
                    if (dataRow["mobile"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "mobile",
                            profilevalue = dataRow["mobile"].ToString(),
                            profileaccess = dataRow["mobile_accessid"].ToString()
                        });
                    }
                    if (dataRow["website"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "website",
                            profilevalue = dataRow["website"].ToString(),
                            profileaccess = dataRow["website_accessid"].ToString()
                        });
                    }
                    if (dataRow["twitter"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "twitter",
                            profilevalue = dataRow["twitter"].ToString(),
                            profileaccess = dataRow["twitter_accessid"].ToString()
                        });
                    }
                    playerModel.profileoptions = list;
                }
            }
            return playerModel;
        }

        public static PlayerModel GetPlayerInfo(int PlayerId)
        {
            PlayerModel playerModel = new PlayerModel();
            DataSet dataSet = new DataSet();
            using (MySqlConnection mySqlConnection = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand mySqlCommand = new MySqlCommand(APIHelper.DBName + "my_getPlayerProfile", mySqlConnection))
                {
                    mySqlCommand.Parameters.Add("UserID", PlayerId);
                    mySqlCommand.CommandType = CommandType.StoredProcedure;
                    using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(mySqlCommand))
                    {
                        mySqlDataAdapter.Fill(dataSet);
                    }
                }
            }
            if (dataSet.Tables.Count > 0)
            {
                DataTable dataTable = dataSet.Tables[1];
                string siteurl = dataSet.Tables[0].Rows[0]["url"].ToString();
                if (dataTable.Rows.Count > 0)
                {
                    DataRow dataRow = dataTable.Rows[0];
                    playerModel.id = new int?(int.Parse(dataRow["UserID"].ToString()));
                    playerModel.name = dataRow["name"].ToString();
                    playerModel.username = dataRow["userName"].ToString();
                    playerModel.email = dataRow["email"].ToString();
                    string linpath = siteurl + "mod/profile/icondirect.php?joindate=" + dataRow["time_created"].ToString() + "&guid=" + playerModel.id + "&size=large";
                    playerModel.photo = linpath;
                    List<ProfileOptions> list = new List<ProfileOptions>();
                    if (DBNull.Value != dataRow["briefdescription"])
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "briefdescription",
                            profilevalue = dataRow["briefdescription"].ToString(),
                            profileaccess = dataRow["briefdescription_accessid"].ToString()
                        });
                    }
                    if (DBNull.Value != dataRow["description"])
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "description",
                            profilevalue = dataRow["description"].ToString(),
                            profileaccess = dataRow["description_accessid"].ToString()
                        });
                    }
                    if (DBNull.Value != dataRow["location"])
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "location",
                            profilevalue = dataRow["location"].ToString(),
                            profileaccess = dataRow["location_accessid"].ToString()
                        });
                    }
                    if (dataRow["interests"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "interests",
                            profilevalue = dataRow["interests"].ToString(),
                            profileaccess = dataRow["interests_accessid"].ToString()
                        });
                    }
                    if (dataRow["skills"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "skills",
                            profilevalue = dataRow["skills"].ToString(),
                            profileaccess = dataRow["skills_accessid"].ToString()
                        });
                    }
                    if (dataRow["contactemail"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "contactemail",
                            profilevalue = dataRow["contactemail"].ToString(),
                            profileaccess = dataRow["contactemail_accessid"].ToString()
                        });
                    }
                    if (dataRow["phone"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "phone",
                            profilevalue = dataRow["phone"].ToString(),
                            profileaccess = dataRow["phone_accessid"].ToString()
                        });
                    }
                    if (dataRow["mobile"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "mobile",
                            profilevalue = dataRow["mobile"].ToString(),
                            profileaccess = dataRow["mobile_accessid"].ToString()
                        });
                    }
                    if (dataRow["website"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "website",
                            profilevalue = dataRow["website"].ToString(),
                            profileaccess = dataRow["website_accessid"].ToString()
                        });
                    }
                    if (dataRow["twitter"] != DBNull.Value)
                    {
                        list.Add(new ProfileOptions
                        {
                            profilekey = "twitter",
                            profilevalue = dataRow["twitter"].ToString(),
                            profileaccess = dataRow["twitter_accessid"].ToString()
                        });
                    }
                    playerModel.profileoptions = list;
                }
            }
            return playerModel;
        }

        public static List<ProfileImage> GetPlayerProfileImagesBinary(int playerid)
        {
            List<ProfileImage> list = new List<ProfileImage>();
            DataSet dataSet = new DataSet();
            using (MySqlConnection connection = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand selectCommand = new MySqlCommand(APIHelper.DBName + "my_getURLPath", connection))
                {

                    selectCommand.Parameters.AddWithValue("pElggEntityGUID", playerid);
                    
                    selectCommand.CommandType = CommandType.StoredProcedure;
                    using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(selectCommand))
                        ((DataAdapter)mySqlDataAdapter).Fill(dataSet);
                }
            }
            if (dataSet.Tables.Count > 0)
            {
                string linpath = "";
                foreach (DataRow dataRow in (InternalDataCollectionBase)dataSet.Tables[0].Rows)
                {
                    linpath = dataRow["url"].ToString() + "mod/profile/icondirect.php?joindate=" + dataRow["time_created"].ToString() + "&guid=" + playerid + "&size=";
                    string imagelarge =new PlayerDomainModles().getbase64(linpath+"large");
                    list.Add(new ProfileImage
                    {

                        imagetype = "large",
                        image = imagelarge
                    });
                    string imagemedium = new PlayerDomainModles().getbase64(linpath + "medium");
                    list.Add(new ProfileImage
                    {

                        imagetype = "medium",
                        image = imagemedium
                    });
                    string imagesmall = new PlayerDomainModles().getbase64(linpath + "samll");
                    list.Add(new ProfileImage
                    {

                        imagetype = "small",
                        image = imagesmall
                    });
                    string imagestiny = new PlayerDomainModles().getbase64(linpath + "tiny");
                    list.Add(new ProfileImage
                    {

                        imagetype = "tiny",
                        image = imagestiny
                    });
                    string imagemaster = new PlayerDomainModles().getbase64(linpath + "master");
                    list.Add(new ProfileImage
                    {

                        imagetype = "master",
                        image = imagemaster
                    });
                    string imagetopbar = new PlayerDomainModles().getbase64(linpath + "topbar");
                    list.Add(new ProfileImage
                    {

                        imagetype = "topbar",
                        image = imagetopbar
                    });
                }
            }
            return list;
        }
        /// <summary>
        /// Image base 64
        /// </summary>
        /// <param name="playerid"></param>
        /// <returns></returns>
        /// 
        public string getbase64(string url)
        {
            StringBuilder _sb = new StringBuilder();
            Byte[] _byte = GetImage(url);

            _sb.Append(Convert.ToBase64String(_byte, 0, _byte.Length));

             return _sb.ToString();
        }

        public byte[] GetImage(string url)
        {
             Stream stream = null;
             byte[] buf;

             try
             {
                  WebProxy myProxy = new WebProxy();
                  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

                  HttpWebResponse response = (HttpWebResponse)req.GetResponse();
                  stream = response.GetResponseStream();

                  using (BinaryReader br = new BinaryReader(stream))
                  {
                       int len = (int)(response.ContentLength);
                       buf = br.ReadBytes(len);
                       br.Close();
                  }

                  stream.Close();
                  response.Close();
             }
             catch (Exception exp)
             {
                  buf = null;
             }

             return (buf);
        }
        public static List<ProfileImage> GetPlayerProfileImages(int playerid)
        {
            List<ProfileImage> list = new List<ProfileImage>();
            DataSet dataSet = new DataSet();
            using (MySqlConnection connection = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand selectCommand = new MySqlCommand(APIHelper.DBName + "my_getURLPath", connection))
                {
                    selectCommand.Parameters.AddWithValue("pElggEntityGUID", playerid);
                    selectCommand.CommandType = CommandType.StoredProcedure;
                    using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(selectCommand))
                        ((DataAdapter)mySqlDataAdapter).Fill(dataSet);
                }
            }
            if (dataSet.Tables.Count > 0)
            {
                string linpath = "";
                foreach (DataRow dataRow in (InternalDataCollectionBase)dataSet.Tables[0].Rows)
                {
                    linpath = dataRow["url"].ToString() + "mod/profile/icondirect.php?joindate=" + dataRow["time_created"].ToString() + "&guid=" + playerid + "&size=";
                    list.Add(new ProfileImage
                    {

                        imagetype = "large",
                        image = linpath + "large"
                    });
                    list.Add(new ProfileImage
                    {

                        imagetype = "medium",
                        image = linpath + "medium"
                    });
                    list.Add(new ProfileImage
                    {

                        imagetype = "small",
                        image = linpath + "small"
                    });
                    list.Add(new ProfileImage
                    {

                        imagetype = "tiny",
                        image = linpath + "tiny"
                    });
                    list.Add(new ProfileImage
                    {

                        imagetype = "master",
                        image = linpath + "master"
                    });
                    list.Add(new ProfileImage
                    {

                        imagetype = "topbar",
                        image = linpath + "topbar"
                    });
                }
            }
            return list;
        }
        public static List<GroupModel> GetGroups(int GroupType)
        {
            List<GroupModel> list = new List<GroupModel>();
            DataSet dataSet = new DataSet();
            using (MySqlConnection connection = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand selectCommand = new MySqlCommand(APIHelper.DBName + "my_getgroup", connection))
                {
                    selectCommand.Parameters.AddWithValue("pgroupType", GroupType);
                    selectCommand.Parameters.AddWithValue("pelgg_entityGuid", DBNull.Value);
                    selectCommand.CommandType = CommandType.StoredProcedure;
                    using (MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(selectCommand))
                        ((DataAdapter)mySqlDataAdapter).Fill(dataSet);
                }
            }
            if (dataSet.Tables.Count > 0)
            {
                foreach (DataRow dataRow in (InternalDataCollectionBase)dataSet.Tables[1].Rows)
                    list.Add(new GroupModel()
                    {
                        id = new int?(int.Parse(dataRow["guid"].ToString())),
                        name = dataRow["gpName"].ToString()
                    });
            }
            return list;
        }
        public static IEnumerable<PlayeronlineModel> GetPlayerstatus(int PlayerId, int Status, int ShowFriends)
        {
            List<PlayeronlineModel> list = new List<PlayeronlineModel>();

            /////////////////

            DataSet dsData = new DataSet();
            using (MySqlConnection con = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(APIHelper.DBName + "my_getloginuser", con))
                {
                    if (PlayerId > 0)
                    {
                        cmd.Parameters.AddWithValue("puserID", PlayerId);

                    }
                    else
                        cmd.Parameters.AddWithValue("puserID", DBNull.Value);
                    if (Status != -100)
                    {
                        bool status;
                        string strstatus;
                        if (Status == 1)
                            strstatus = "true";
                        else
                            strstatus = "false";

                        bool.TryParse(strstatus, out status);
                        cmd.Parameters.AddWithValue("pStatus", status);
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue("pStatus", DBNull.Value);
                    }

                    bool showfriends;
                    string strshowfriends;
                    if (ShowFriends == 1)
                        strshowfriends = "true";
                    else
                        strshowfriends = "false";

                    bool.TryParse(strshowfriends, out showfriends);
                    cmd.Parameters.AddWithValue("pShowFriend", showfriends);


                    cmd.CommandType = CommandType.StoredProcedure;
                    using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                    {

                        da.Fill(dsData);
                        //return dsData;
                    }
                }
            }
            if (dsData.Tables.Count > 0)
            {
                DataTable dt = dsData.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {

                        PlayeronlineModel Player = new PlayeronlineModel();
                        Player.id = int.Parse(dr["guid"].ToString());
                        Player.name = dr["name"].ToString();
                        Player.username = dr["userName"].ToString();
                        //bool onlinestatus;
                        //bool.TryParse(dr["OnlineStatus"].ToString(), out onlinestatus);
                        Player.onlinstatus = dr["OnlineStatus"].ToString();
                        list.Add(Player);
                    }
                }
            }

            ////////////////

            IEnumerable<PlayeronlineModel> playerlist = list;
            return playerlist;


        }

        public static PlayerMetrics GetGameMetrics(int PlayerId, int GameId)
        {
            PlayerMetrics playermetrics = new PlayerMetrics();
            DataSet dsData = new DataSet();
            using (MySqlConnection con = new MySqlConnection(APIHelper.ConnectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand(APIHelper.DBName + "my_getgameMetrics", con))
                {
                    cmd.Parameters.AddWithValue("pElggEntityGUID", PlayerId);
                    cmd.Parameters.AddWithValue("pGameID", GameId);
                    cmd.CommandType = CommandType.StoredProcedure;
                    using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                    {
                        da.Fill(dsData);
                    }
                }
            }
            if (dsData.Tables.Count > 0)
            {
                DataTable dt = dsData.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    playermetrics.gameid = GameId;
                    playermetrics.playerid = PlayerId;
                    playermetrics.gamemetrics = dr["GameMetrics"].ToString();

                }
            }

            return playermetrics;

        }
    }

}
